<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once 'Uploader.php';

/**
 * Extension of the abstract Uploader class for image files.
 * 
 * @todo make this more extendable, right now the configurations are very focused. 
 * 
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Libraries
 * @author David Morris
 * @see Uploader
 */
class ImageUploader extends Uploader {
    
    private $MaxCropSide = 150;
    private $ThumbConfig;
    
    public function __construct($Args) {
        parent::__construct($Args);
        $this->ThumbConfig = array(
            'image_library' => 'GD2','create_thumb' => TRUE, 
            'maintain_ratio' => FALSE, 'width' => $this->MaxCropSide,
            'height' => $this->MaxCropSide, 'dest_image' => $this->Dir,
            'thumb_marker' => '_thumb', 'quality' => 80 
        );
//die(var_dump($this->ThumbConfig));        
        
    }

    /**
     * Basically provides an way of inserting images. Images are created with a unique filename
     * a thumbnail is also created for that image. The image is then uploaded to the generic images_table,
     * before being inserted to it's more focused table as a foreign key
     * 
     * @param string $formField the file upload element
     * @param array $dbFieldsValues the assocative array for values for insertion "column" => "value"
     * @param string caption for the image
     * @return int the new file id
     */
    public function insert($formField, $dbFieldsValues = array(), $caption = '')
    {     
        $fileName = $this->moveFile($formField);
        if($fileName === false)
            return $fileName;
        $this->ThumbConfig['source_image'] = $this->Dir.$fileName;
        $this->CI->load->library('image_lib', $this->ThumbConfig);
        $thumbName = $this->createThumbnail();
        if(!$thumbName)
            return false; // TODO exception   
        $imageDetails = getimagesize($this->Dir.$fileName);        
        list($imgWidth, $imgHeight, $imgType) = $imageDetails;
        
        $this->CI->db->query('INSERT INTO images_table (image_type, image_location, image_thumb,
            image_width, image_height, image_caption, image_uploaded, image_owner ) 
            VALUES (?, ?, ?, ?, ?, ?, UNIX_TIMESTAMP(), 1)',
            array($imgType, $this->Dir.'/'.$fileName, $thumbName, $imgWidth, $imgHeight, $caption));
        
        $newFileId = $this->CI->db->insert_id();
        $dbFieldsValues[$this->Field] = $newFileId;
        $columns = $this->prepareColumns(array_keys($dbFieldsValues));
        $values = implode(', ',array_pad(array(),count($dbFieldsValues),'?'));
        $this->CI->db->query('INSERT INTO `'.$this->Table.'` ('.$columns.') VALUES ('.$values.')',
            array_values($dbFieldsValues));
        
        return $newFileId;
    }
    
    /**
     * Creates a new square thumbnail of the image provided at the location in
     * $Source and returns it's name and location. Images not scaled with ratio
     * intact.
     * 
     * @return string filename
     */
    private function createThumbnail()
    {

        if(!$this->CI->image_lib->resize())
        {
            echo $this->CI->image_lib->display_errors('<p>', '</p>');
            return false;
        }
        $pathInfo = pathinfo($this->ThumbConfig['source_image']);       
        return $pathInfo['dirname'].'/'.$pathInfo['filename'].$this->ThumbConfig['thumb_marker'].'.'.$pathInfo['extension'];
        
    }
    
}
// END OF FILE